package util

import (
	"bytes"
	"github.com/sirupsen/logrus"
	"io/ioutil"
	"net/http"
)

func Get(url string, requestLog bool) []byte {
	if requestLog {
		logrus.Print("请求地址:" + url)
	}
	resp, err := http.Get(url)
	if err != nil {
		logrus.Error("Error:", err)
		return nil
	}
	defer resp.Body.Close()
	if resp.StatusCode == 404 {
		logrus.Print("404 Group Not Found")
	}
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		logrus.Print("Error:", err)
		return nil
	}
	if requestLog {
		logrus.Print("响应结果:", string(body))
	}
	return body
}

func Get2(url string, token string, requestLog bool) []byte {
	if requestLog {
		logrus.Print("请求地址:" + url)
	}
	request, e := http.NewRequest("GET", url, nil)
	if e != nil {
		logrus.Error("create request err:", e)
		return nil
	}
	if token != "" {
		request.Header.Set("PRIVATE-TOKEN", token)
	}
	client := &http.Client{}
	response, e := client.Do(request)
	if e != nil {
		logrus.Error("send reqeust err:", e)
		return nil
	}
	defer response.Body.Close()
	body, e := ioutil.ReadAll(response.Body)
	if e != nil {
		logrus.Error("response err:", e)
		return nil
	}
	if requestLog {
		logrus.Print("响应结果:", string(body))
	}
	return body
}

func Post(url string, data []byte, token string, requestLog bool) []byte {
	if requestLog {
		logrus.Print("请求地址:", url)
	}
	body := execRequest("POST", token, url, data)
	if requestLog {
		logrus.Print("响应结果:", string(body))
	}
	return body
}

func Put(url string, data []byte, token string, requestLog bool) []byte {
	if requestLog {
		logrus.Print("请求地址:", url)
	}
	body := execRequest("PUT", token, url, data)
	if requestLog {
		logrus.Print("响应结果:", string(body))
	}
	return body
}

func execRequest(httptype string, token string, url string, data []byte) []byte {
	request, e := http.NewRequest(httptype, url, bytes.NewBuffer(data))
	request.Header.Set("Content-Type", "application/json")
	request.Header.Set("PRIVATE-TOKEN", token)
	client := &http.Client{}
	response, e := client.Do(request)
	if e != nil {
		logrus.Error("send request err:", e)
	}
	defer response.Body.Close()
	body, e := ioutil.ReadAll(response.Body)
	if e != nil {
		logrus.Error("response err:", e)
		return nil
	}
	return body
}
